<template>
  <div id="app">
    <router-view/>
    <msg-notice-dialog/>
  </div>
</template>

<script>

import {noticeApi} from '@/feature/mms/infra/api/noticeApi'
import {voteBadCommentApi} from '@/feature/cmt/infra/api/voteBadCommentApi'
import {EventBus} from '@/framework/infra/event/EventBus'
import EventNames from '@/infra/event/EventNames'
import {complainFollowUpApi} from '@/feature/cmt/infra/api/complainFollowUpApi'
import MsgNoticeDialog from '@/components/Msg/MsgNoticeDialog'
import {deliveryComplainApi} from '@/feature/cmt/infra/api/deliveryComplainApi'
import {EventSourcePolyfill} from 'event-source-polyfill'
import {getToken} from '@/utils/auth'
import FluxApi from '@/feature/pdt/infra/api/FluxApi'
import {refreshToken} from '@/infra/api/user'
import {AppVersion} from '@/framework/constant/Common'

export default {
  name: 'App',
  components: {MsgNoticeDialog},
  created() {
    EventBus.on(EventNames.onFresh, this.startFetch)
    EventBus.on(EventNames.logoff, this.logoff)
    EventBus.on(EventNames.sessionOut, this.sessionOut)
    this.timeFlag = {}
  },
  destroyed() {
    this.clearSSE()
  },
  methods: {
    startFetch() {
      // if (process.env.VUE_APP_TIME_DISABLE) {
      //   return
      // }
      // this.startCount()
      // FluxApi.countInfo().then(data => {
      //   this.setCountData(data)
      // })
      // this.setSSE()
      this.startRefreshTask()
    },
    clearRefreshTask() {
      if (this.flag) clearInterval(this.flag)
    },
    startRefreshTask() {
      // console.log('startRefreshTask')
      this.clearRefreshTask()
      // 30分钟刷新一次token
      refreshToken()
      this.flag = setInterval(() => {
          refreshToken()
        },
        10 * 60 * 1000
      )
    },
    logoff() {
      // Object.values(this.timeFlag).forEach(flag => {
      //   clearTimeout(flag)
      // })
      // this.timeFlag = {}
      this.clearSSE()
      this.clearRefreshTask()
    },
    sessionOut() {
      this.$alert('会话已过期,请重新登录', '提示', {
        callback: action => {
          this.$store.dispatch('user/logout').then(() => {
            this.$router.replace(`/login?redirect=${this.$route.fullPath}`)
          })
        }
      })
    },
    setCountData(items) {
      let item = items.find(el => el.type === 'unReadMsgCount')
      if (item) {
        this.$store.commit('app/setUnReadMsgCount', item.data)
      }
      item = items.find(el => el.type === 'voteBadCommentCount')
      if (item) {
        this.$store.commit('app/setBadCommentDataCount', voteBadCommentApi.parseDataCount(item.data))
      }
      item = items.find(el => el.type === 'deliveryComplainCount')
      if (item) {
        this.$store.commit('app/setDeliveryDataCount', deliveryComplainApi.parseDataCount(item.data))
      }
      item = items.find(el => el.type === 'complainFollowUpCount')
      if (item) {
        this.$store.commit('app/setComplainDataCount', complainFollowUpApi.parseDataCount(item.data))
      }
      item = items.find(el => el.type === 'competingStoreBloggerCount')
      if (item) {
        this.$store.commit('app/setCompetingStoreBloggerCount', {
          count: item.data
        })
      }
    },
    clearSSE() {
      if (this.eventSource) {
        this.eventSource.close()
        this.eventSource = null
      }
    },
    setSSE() {
      const eventSource = new EventSourcePolyfill(`${location.origin}/flux-api/v1/stream`, {
        headers: {
          'Authorization': getToken(),
          'token': getToken(),
          'AppVersion': AppVersion
        }
      })
      eventSource.onmessage = (event) => {
        console.log(event)
        const data = typeof event.data === 'string' ? JSON.parse(event.data) : {}
        if (data.code === 200) {
          this.setCountData(data.data)
        } else if (data.code === 2001) {
          EventBus.emit(EventNames.sessionOut)
          this.clearSSE()
        }
      }
      eventSource.onerror = (event) => {
        console.log(event)
        // 错误，重新连接
        this.clearSSE()
        setTimeout(() => {
          this.setSSE()
        }, 4000)
      }
      this.eventSource = eventSource
    },
    startCount() {
      this.logoff()
      const noticeSync = () => {
        noticeApi.sync().then((newMsgFlag) => {
          this.$store.dispatch('app/fetchUnReadMsgCount')
          // if (newMsgFlag) {
          //   EventBus.emit(EventNames.newMsg)
          // }
        })
        this.timeFlag.noticeSync = setTimeout(noticeSync, 4200)
      }
      noticeSync()
      const voteBadCommentDataCount = () => {
        voteBadCommentApi.dataCount().then((data) => {
          this.$store.commit('app/setBadCommentDataCount', data)
        })
        this.timeFlag.voteBadCommentDataCount = setTimeout(voteBadCommentDataCount, 4000)
      }
      voteBadCommentDataCount()

      const deliveryComplainDataCount = () => {
        deliveryComplainApi.dataCount().then((data) => {
          this.$store.commit('app/setDeliveryDataCount', data)
        })
        this.timeFlag.deliveryComplainDataCount = setTimeout(deliveryComplainDataCount, 4500)
      }
      deliveryComplainDataCount()

      const complainFollowUpDataCount = () => {
        complainFollowUpApi.dataCount().then(data => {
          this.$store.commit('app/setComplainDataCount', data)
        })
        this.timeFlag.complainFollowUpDataCount = setTimeout(complainFollowUpDataCount, 3000)
      }
      complainFollowUpDataCount()
    }
  }
}
</script>
